package com.qingcloud.common.auth.email;

import cn.hutool.extra.spring.SpringUtil;
import com.qingcloud.common.auth.service.impl.UserDetailServiceFactory;
import com.qingcloud.common.auth.token.EmailAuthenticationToken;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Objects;


@Setter
@Getter
@Slf4j
public class EmailAuthenticationProvider implements AuthenticationProvider {
    private static final String VERIFY_LONG_PREFIX = "qingcloud:register:verify:long:";

    private UserDetailServiceFactory userDetailsServiceFactory;

    @Override
    public Authentication authenticate(Authentication authentication) {
        EmailAuthenticationToken authenticationToken = (EmailAuthenticationToken) authentication;
        String email = (String) authenticationToken.getPrincipal();
        String verifyCode = (String) authenticationToken.getCredentials();
        UserDetails user = userDetailsServiceFactory.getService(authenticationToken).loadUserByMobile(email);
        if (user == null) {
            throw new InternalAuthenticationServiceException("邮箱或验证码错误");
        }
        StringRedisTemplate stringRedisTemplate = SpringUtil.getBean(StringRedisTemplate.class);
        String redisValue = stringRedisTemplate.opsForValue().get(VERIFY_LONG_PREFIX + email);
        log.info("{} verify code is {}", email, redisValue);
        if (Objects.isNull(redisValue) || !redisValue.equals(verifyCode)) {
            throw new InternalAuthenticationServiceException("邮箱或验证码错误");
        }
        EmailAuthenticationToken authenticationResult = new EmailAuthenticationToken(user, verifyCode, user.getAuthorities());
        authenticationResult.setDetails(authenticationToken.getDetails());
        return authenticationResult;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return EmailAuthenticationToken.class.isAssignableFrom(authentication);
    }
}
